package cn.jolyoulu.common.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author LuZhouJin
 * @Date 2023/5/25
 * 跨域配置
 */
@Configuration
public class CorsConfig {

    // 环境
    @Value(value = "${spring.profiles.active}")
    private String env;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(false);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    /**
     * 跨域过滤器
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // dev环境下，代码中开启跨域，其它环境nginx中配置跨域
        if("dev".equals(env)){
            source.registerCorsConfiguration("/**", buildConfig()); // 4
        }
        CorsFilter filter = new CorsFilter(source);
        return filter;
    }

}
